import { token, userInfo, imInfo, currentImInfo } from "@/utils/token.js"
import { appId, sdkAppId } from "@/config.js"
// import IMController from '@/libs/imController.js'
import TxyImController from '@/libs/txy-im/txyImController.js'

const app = getApp()
export default {
	data() {
		return {
			durationList: [
				{ name: '一周内', value: 0 },
				{ name: '一月内', value: 1 },
				{ name: '半年内', value: 2 },
				{ name: '半年以上', value: 3 }
			],
			isLookHospList: [
				{ name: '未就诊', value: 0 },
				{ name: '就诊过', value: 1 },
			],
			orderTypeList: [
				{ name: '专家问诊', value: 0 },
				{ name: '极速问诊', value: 1 },
				{ name: '开药问诊', value: 2 },
			],
			inquiryTypeList: [
				{ name: '图文问诊', value: 0 },
				{ name: '视频问诊', value: 1 }
			],

			birthStatusList: [
				{ name: '无', value: 0 },
				{ name: '准备要孩子', value: 1 },
				{ name: '怀孕中', value: 2 },
				{ name: '正在哺乳', value: 3 }
			],

			functionList: [
				{ name: '正常', value: 0 },
				{ name: '异常', value: 1 },
				{ name: '不清楚', value: 2 }
			],
			allergyList: [
				{ name: '无', value: 0 },
				{ name: '有', value: 1 },
				{ name: '不清楚', value: 2 }
			],
			rangeSex: [
				{ value: 0, text: '男' },
				{ value: 1, text: '女' }
			],
			jobGradeConfig: ['医师', '医士', '住院医师', '主治医师', '副主任医师', '主任医师', '药士', '药师', '主管药师', '副主任药师', '主任药师'],
			checkStatusConfig: ['认证中', '已认证', '已驳回'],
			orderStatusList: ["支付中", "支付成功", "支付失败", "待支付", "退款中", "已退款", "已取消", "待发货", "待收货", "已评价", "已完成"],
			qStatusList: ["待接诊", "问诊中", "已开处方", "已完成", "已退诊"],
			recipeStatusList: ["待审核", "已审核", "已购买", "已失效", "审核未通过"]
		}
	},
	computed: {},
	onLoad(options) {
		//im校验
		/*
		if (!getApp().globalData.nim) {
			this.initIm(imInfo.get().token, imInfo.get().accid)
		}
		*/
	   
		if (!getApp().globalData.txyImController) {
			this.initTxyIm(sdkAppId)
			// getApp().globalData.txyImController.login(currentImInfo.get().id, currentImInfo.get().userSig)
		}
		
		//开启小程序分享
		uni.showShareMenu({
			title: '',
			path: options.path,
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
	},
	onShareAppMessage() {
		return {
			title: '',
			success: res => {
				uni.showToast({
					title: '分享成功'
				});
			},
			fail: err => {
				uni.showToast({
					title: '分享失败',
					icon: 'none'
				});
			}
		};
	},
	methods: {
		//路由跳转
		gotoRouter(url, data = null) {
			if (!token.get()) {
				this.wxLogin()
			} else {
				uni.navigateTo({
					url: url,
					success: res => {
						if (data) {
							res.eventChannel.emit('data', data);
						}
					},
					fail: err => {
						// console.log(err)
						uni.switchTab({
							url: url
						});
					}
				});
			}
		},

		//初始化im
		/*
		initIm(token, accid) {
			this.$store.commit('im/setSessions', [])
			// console.log("init im")
			// console.log(token)
			// console.log(accid)
			new IMController({
				token: token,
				account: accid
			});
		},
		*/

		//初始化腾讯云IM
		initTxyIm(sdkAppId, userId, userSig) {
			getApp().globalData.txyImController = new TxyImController({
				sdkAppId
			})
		},

		//微信登录
		wxLogin(e) {
			uni.navigateTo({
				url:'/pages-mall/login/login'
			})
			return
			uni.showLoading({
				title: '登录中...',
				mask: true
			});
			
			// 尝试静默登录
			this.wxSilentLogin().then(res => {
				this.$api.wxLogin({
					data: {
						appId,
						code: res,
						parentUserId : getApp().globalData.parentUserId
					}
				}).then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						uni.showToast({
							title: "登录成功",
							icon: 'none'
						})
						imInfo.set(res.result.imInfo, Date.parse(new Date()) + (86400000 * 29));
						token.set(res.result.token, Date.parse(new Date()) + (86400000 * 29));
						userInfo.set(res.result.wxUser, Date.parse(new Date()) + (86400000 * 29));
						currentImInfo.set(res.result.imInfo, Date.parse(new Date()) + (86400000 * 29));
						// this.initIm(res.result.imInfo.token, res.result.imInfo.accid)
						getApp().globalData.role = res.result.wxUser.currentRole;
						if (!getApp().globalData.txyImController) {
							this.initTxyIm(parseInt(res.result.imInfo.sdkAppId))
							// getApp().globalData.txyImController.login(currentImInfo.get().id, currentImInfo.get().userSig)
						}
						getApp().globalData.txyImController.login(res.result.imInfo.id, res.result.imInfo.userSig)
					} else if (res.code == 406) {
						// 新用户，需要走注册流程
						uni.navigateTo({
							url:'/pages-mall/login/login'
						})
						
					} else if (res.code == 405) {
						// 需要授权获取手机号
						uni.navigateTo({
							url:'/pages-mall/login/login'
						})
					}
				})
			})
		},
		wxGetUserProfile() {
			return new Promise((resolve, reject) => {
				wx.getUserProfile({
					lang: 'zh_CN',
					desc: '用户登录',
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		},
		wxSilentLogin() {
			return new Promise((resolve, reject) => {
				wx.login({
					success(res) {
						resolve(res.code)
					},
					fail(err) {
						reject(err)
					}
				})
			})
		},
		//复制内容到剪切版
		setClipboardData(data) {
			uni.setClipboardData({
				data: data,
				success: res => {
					uni.showToast({
						title: '复制成功',
						icon: "none"
					});
				}
			});
		},

		/**
		 * 添加好友
		 */
		/*
		addFriendBtnHandler() {
			let account = this.data.user.account
			app.globalData.nim.addFriend({
				account,
				ps: '',
				done: (err, obj) => {
					if (err) {
						console.log(err)
						return
					}

					// 获取名片信息
					app.globalData.nim.getUser({
						account,
						done: function(err, user) {
							store.dispatch({
								type: 'FriendCard_Add_Friend',
								payload: user
							})
							// 订阅后只有在订阅账号登录状态变化后才会收到推送事件
							app.globalData.nim.subscribeEvent({
								type: 1, // 订阅用户登录状态事件
								accounts: new Array(account),
								subscribeTime: 3600 * 24 * 30,
								sync: true,
								done: function(err, obj) {
									if (err) {
										console.log(err)
										return
									}
									console.log(obj) // {failedAccounts: Array(0)}
								}
							})
							wx.switchTab({
								url: '../../pages/contact/contact'
							})
						}
					})
				}
			})
		},
		*/

		/**
		 * 发送请求，删除好友
		 */
		/*
		doDeleteFriend() {
			let self = this
			app.globalData.nim.deleteFriend({
				account: self.data.userCard.account,
				done: (err, obj) => {
					if (err) {
						console.log(err)
						return
					}
					store.dispatch({
						type: 'FriendCard_Delete_By_Account',
						payload: self.data.userCard.account
					})
					wx.switchTab({
						url: '../../pages/contact/contact',
					})
				}
			})
		},
		*/

		/**
		 * 聊天按钮
		 */
		chatBtnHandler() {
			// 更新会话对象
			store.dispatch({
				type: 'CurrentChatTo_Change',
				payload: 'p2p-' + this.data.userCard.account
			})
		},

		//预览图片
		previewImage(imgs, index) {
			uni.previewImage({
				urls: imgs,
				loop: true,
				current: index
			});
		},

		// 获取会话列表
		fetchConversationList() {
			getApp().globalData.tim.getConversationList()
				.then(imResponse => {
					this.conversationList = imResponse.data.conversationList; 
				}).catch(imError => {
					console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
				});
		},
		
		// 动态跳转（redirectType  1：无链接 2：小程序内链 3：小程序外链 4：H5外链）
		dynamicJump(menu) {
			switch (menu.redirectType) {
				case 2:
					this.gotoRouter(menu.redirectUrl);
					break;
				case 3:
					uni.navigateToMiniProgram({
						appId: menu.appId,
						path: mune.redirectUrl
					});
					break;
				case 4:
					this.gotoRouter('/pages/webHome/webHome?url='+menu.redirectUrl);
					break;
			}
		}
	}
}
